package com.shjl.kechuang.utils;

import com.shjl.kechuang.domain.pojo.KySpecSme;
import com.shjl.kechuang.domain.pojo.KyTechSme;
import com.shjl.kechuang.mapper.KySpecSmeMapper;
import com.shjl.kechuang.mapper.KyTechSmeMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @title: PdfReader
 * @author: wywang
 * @date: 2025/04/07
 * @description:  读取PDF文件,写入数据库
 * @version: 1.0
 **/
@Slf4j
@Component
public class PdfReader {

    @Autowired
    private KyTechSmeMapper kyTechSmeMapper;

    @Autowired
    private KySpecSmeMapper kySpecSmeMapper;

    /**
     * 读取PDF文件,写入数据库(通用)
     * @param fileName
     * @param kyTechSme
     */
    public void readerPDFtoSQL(String fileName, KyTechSme kyTechSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);
                List<KyTechSme> techSmes = new ArrayList<>();

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("撤销")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "").trim();
                    // 分割企业名称和入库编号
                    String[] parts = cleanedLine.split("\\s+(?=\\S+$)");
                    if(parts[0].contains("序号")){
                        continue;
                    }
                    if (parts.length == 2) { // 确保正确分割
                        String companies = parts[0].trim();
                        String storeNumber = parts[1].trim();

                        KyTechSme techSme = KyTechSme.builder()
                                .companies(companies)
                                .storeNumber(storeNumber)
                                .province(kyTechSme.getProvince())
                                .pubYear(kyTechSme.getPubYear())
                                .batch(kyTechSme.getBatch())
                                .dr(0)
                                .updateTime(new Date())
                                .build();


                        techSmes.add(techSme);
                    }

                }
                int batchSize = 100;
                for (int i = 0; i < techSmes.size(); i += batchSize) {
                    List<KyTechSme> subList = techSmes.subList(i, Math.min(i + batchSize, techSmes.size()));
                    kyTechSmeMapper.batchInsert(subList);
                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            System.out.println("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }


    /**
     * 读取PDF文件,写入数据库(吉林)
     * @param fileName
     * @param kyTechSme
     */
    public void readerPDFtoSQLJiLin(String fileName, KyTechSme kyTechSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);
                List<KyTechSme> techSmes = new ArrayList<>();

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("撤销")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                            .replaceAll("\\s+", " ")               // 合并多余空格
                            .trim();                               // 去掉首尾空格

                    // 打印调试信息
                    System.out.println("Cleaned Line: '" + cleanedLine + "'");

                    // 使用正则表达式匹配企业名称、统一社会信用代码和入库编号
                    Pattern pattern = Pattern.compile("^(.*?)\\s+(\\d{18})\\s+(\\S+)$");
                    Matcher matcher = pattern.matcher(cleanedLine);

                    String[] split = cleanedLine.split(" ");
                    if (split.length < 3){
                        continue;
                    }

                    //if (matcher.find()) {
                        String companies = split[0].trim(); // 企业名称
                        String storeNumber = split[2].trim();  // 入库编号

                        KyTechSme techSme = KyTechSme.builder()
                                .companies(companies)
                                .storeNumber(storeNumber)
                                .province(kyTechSme.getProvince())
                                .pubYear(kyTechSme.getPubYear())
                                .batch(kyTechSme.getBatch())
                                .dr(0)
                                .updateTime(new Date())
                                .build();


                        techSmes.add(techSme);
                    //}

                }
                int batchSize = 100;
                for (int i = 0; i < techSmes.size(); i += batchSize) {
                    List<KyTechSme> subList = techSmes.subList(i, Math.min(i + batchSize, techSmes.size()));
                    kyTechSmeMapper.batchInsert(subList);
                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            System.out.println("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }


    /**
     * 读取PDF文件,写入数据库(吉林1)
     * @param fileName
     * @param kyTechSme
     */
    public void readerPDFtoSQLJiLin1(String fileName, KyTechSme kyTechSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);
                List<KyTechSme> techSmes = new ArrayList<>();

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("撤销")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                            .replaceAll("\\s+", " ")               // 合并多余空格
                            .trim();                               // 去掉首尾空格

                    String[] split = cleanedLine.split(" ");
                    if (split.length < 4){
                        continue;
                    }

                    //if (matcher.find()) {
                    String companies = split[0].trim(); // 企业名称
                    String storeNumber = split[3].trim();  // 入库编号

                    KyTechSme techSme = KyTechSme.builder()
                            .companies(companies)
                            .storeNumber(storeNumber)
                            .province(kyTechSme.getProvince())
                            .pubYear(kyTechSme.getPubYear())
                            .batch(kyTechSme.getBatch())
                            .dr(0)
                            .updateTime(new Date())
                            .build();


                    techSmes.add(techSme);
                    //}

                }
                int batchSize = 100;
                for (int i = 0; i < techSmes.size(); i += batchSize) {
                    List<KyTechSme> subList = techSmes.subList(i, Math.min(i + batchSize, techSmes.size()));
                    kyTechSmeMapper.batchInsert(subList);
                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            System.out.println("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }


    /**
     * 读取pdf文件，写入数据库(山东)
     * @param fileName
     * @param kyTechSme
     */
    public void readerPDFtoSQLShanDong(String fileName, KyTechSme kyTechSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);
                List<KyTechSme> techSmes = new ArrayList<>();

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("撤销")){
                        continue;
                    }
                    if(line.contains("序号")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                            .replaceAll("\\s+", " ")               // 合并多余空格
                            .trim();                               // 去掉首尾空格

                    String[] split = cleanedLine.split(" ");
                    if (split.length < 3){
                        continue;
                    }

                    String companies = split[0].trim(); // 企业名称
                    String storeNumber = split[2].trim();  // 入库编号

                    KyTechSme techSme = KyTechSme.builder()
                            .companies(companies)
                            .storeNumber(storeNumber)
                            .province(kyTechSme.getProvince())
                            .pubYear(kyTechSme.getPubYear())
                            .batch(kyTechSme.getBatch())
                            .dr(0)
                            .updateTime(new Date())
                            .build();


                    techSmes.add(techSme);

                }
                int batchSize = 100;
                for (int i = 0; i < techSmes.size(); i += batchSize) {
                    List<KyTechSme> subList = techSmes.subList(i, Math.min(i + batchSize, techSmes.size()));
                    kyTechSmeMapper.batchInsert(subList);
                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            System.out.println("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }


    /**
     * 读取pdf文件，写入数据库(江苏)
     * @param fileName
     * @param kyTechSme
     */
    public void readerPDFtoSQLJiangSu(String fileName, KyTechSme kyTechSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);
                List<KyTechSme> techSmes = new ArrayList<>();

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("撤销")){
                        continue;
                    }
                    if(line.contains("序号")){
                        continue;
                    }
                    if(line.contains("第")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                            .replaceAll("\\s+", " ")               // 合并多余空格
                            .trim();                               // 去掉首尾空格

                    String[] split = cleanedLine.split(" ");
                    if (split.length < 2){
                        continue;
                    }

                    String companies = split[0].trim(); // 企业名称

                    KyTechSme techSme = KyTechSme.builder()
                            .companies(companies)
                            .storeNumber("")
                            .province(kyTechSme.getProvince())
                            .pubYear(kyTechSme.getPubYear())
                            .batch(kyTechSme.getBatch())
                            .dr(0)
                            .updateTime(new Date())
                            .build();


                    techSmes.add(techSme);

                }
                int batchSize = 100;
                for (int i = 0; i < techSmes.size(); i += batchSize) {
                    List<KyTechSme> subList = techSmes.subList(i, Math.min(i + batchSize, techSmes.size()));
                    kyTechSmeMapper.batchInsert(subList);
                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            System.out.println("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取pdf文件，写入数据库(江苏)
     * @param fileName
     * @param kyTechSme
     */
    public void readerPDFtoSQLJiangSu1(String fileName, KyTechSme kyTechSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);
                List<KyTechSme> techSmes = new ArrayList<>();

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("撤销")){
                        continue;
                    }
                    if(line.contains("序号")){
                        continue;
                    }
                    if(line.contains("第")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                            .replaceAll("\\s+", " ")               // 合并多余空格
                            .trim();                               // 去掉首尾空格

                    String[] split = cleanedLine.split(" ");
                    if (split.length < 3){
                        continue;
                    }

                    String companies = split[0].trim(); // 企业名称
                    String storeNumber = split[2].trim(); // 入库编号

                    KyTechSme techSme = KyTechSme.builder()
                            .companies(companies)
                            .storeNumber(storeNumber)
                            .province(kyTechSme.getProvince())
                            .pubYear(kyTechSme.getPubYear())
                            .batch(kyTechSme.getBatch())
                            .dr(0)
                            .updateTime(new Date())
                            .build();


                    techSmes.add(techSme);

                }
                int batchSize = 100;
                for (int i = 0; i < techSmes.size(); i += batchSize) {
                    List<KyTechSme> subList = techSmes.subList(i, Math.min(i + batchSize, techSmes.size()));
                    kyTechSmeMapper.batchInsert(subList);
                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            System.out.println("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }


    public void readerPDFtoSQLAnHui(String fileName, KySpecSme kySpecSme) {

        try {
            PDDocument loadPDF = Loader.loadPDF(new File(fileName));
            if (!loadPDF.isEncrypted()) {
                PDFTextStripper pdfStripper = new PDFTextStripper();

                String data = pdfStripper.getText(loadPDF);

                String[] lines = data.split("\n");
                for (String line : lines) {

                    if(line.contains("名单")){
                        continue;
                    }
                    if(line.contains("序号")){
                        continue;
                    }
                    // 去掉行首的序号和空格
                    String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                            .replaceAll("\\s+", " ")               // 合并多余空格
                            .trim();                               // 去掉首尾空格

                    kySpecSme.setCompanies(cleanedLine);

                    kySpecSmeMapper.insert(kySpecSme);

                }
                log.info("PDF文件成功写入数据库，文件名：{}", fileName);

            }
        } catch (IOException e) {
            log.info("读取PDF文件失败！");
            throw new RuntimeException(e);
        }
    }
}
